package org.example.day11;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.9.1: 公平锁 与 非公平锁
 *      公平锁: FIFO
 */
public class MyThread5 {
    private ReentrantLock lock;

    public MyThread5(boolean isFair) {
        //公平锁
        lock = new ReentrantLock(isFair);
    }

    public void serviceMethod() {
        try {
            lock.lock();
            System.out.println("ThreadName = " + Thread.currentThread().getName() + "获得锁");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final MyThread5 m5 = new MyThread5(true);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("★ThreadName = " + Thread.currentThread().getName() + "运行了");
                m5.serviceMethod();
            }
        };
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
    }
}
